package blue.tools.commons;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by jianshan on 2018/1/14.
 */
public class Md5Utils {


    public static String getMD5(String data) {
        try {
            if(StringUtils.isBlank(data)){
                return StringUtils.EMPTY;
            }
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            return StringUtils.EMPTY;
        }
    }


    public static String getFileMD5String(FileInputStream in,Integer fileLength) throws Exception{
        MessageDigest messagedigest =MessageDigest.getInstance("MD5");
        FileChannel ch =in.getChannel();
        MappedByteBuffer byteBuffer =ch.map(FileChannel.MapMode.READ_ONLY, 0,fileLength);
        messagedigest.update(byteBuffer);
        BigInteger bigInt = new BigInteger(1, messagedigest.digest());
        return bigInt.toString(16);
    }

}
